﻿using System.Collections.Generic;
using System.Linq;
using Noesis.Javascript;

namespace ReguLiteCM
{
	/// <summary>
	/// 
	/// </summary>
	internal class JavascriptRegexStrategy : IRegexStrategy
	{
		private string _expression;
		private string _input;

		/// <summary>
		/// 
		/// </summary>
		public bool Global{get;set;}
		
		/// <summary>
		/// 
		/// </summary>
		public bool IgnoreCase{get;set;}

		/// <summary>
		/// 
		/// </summary>
		public bool MultiLine{get;set;}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="expression"></param>
		/// <param name="input"></param>
		public JavascriptRegexStrategy(string expression, string input)
		{
			_expression = expression;
			_input = input;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public IEnumerable<string> FindMatches()
		{
			using (JavascriptContext js = new JavascriptContext())
			{
				js.SetParameter("buffer", _input);
				string script = string.Format("buffer.match(/{0}/{1}{2}{3})", _expression,
																																			 Global ? "g" : string.Empty,
																																			 IgnoreCase ? "i" : string.Empty,
																																			 MultiLine ? "m" : string.Empty);
				// Expected: returns array of strings which are the matches found
				object[] matches = js.Run(script) as object[];

				if (matches != null && matches.Length > 0)
				{
					return matches.Select(m => m.ToString()).ToList();
				}

				return null;
			}
		}
	}
}